import { cssObject, onInitialized, storageStore } from '@shared/context'
import { heartbeatDetection, sendTabMessage } from '@shared/serverMessage'
import { Certificate, PostMessageType } from '@shared/types'
import { watch } from 'vue'

function isUrl(txt?: string) {
  return txt?.startsWith('http')
}

function sendCSSInject(tabId: number) {
  sendTabMessage(tabId, {
    type: PostMessageType.DATA,
    data: cssObject.value.css
  })
}

// const SWAGGER_REGISTER_ID = 'swaggerdts'
// function registerSwagger() {
//   const origins = storageStore.docsApis.map(({ origin }) => origin)

//   origins.length &&
//     chrome.scripting.registerContentScripts([
//       {
//         id: SWAGGER_REGISTER_ID,
//         matches: origins,
//         runAt: 'document_end',
//         allFrames: true,
//         css: ['content/style.css'],
//         js: ['content/index.js']
//       }
//     ])
// }

onInitialized(() => {
  watch(cssObject, () => {
    chrome.tabs.query({ status: 'complete', active: true }).then((list) => {
      list.forEach(({ url, id: tabId }) => {
        isUrl(url) && sendCSSInject(tabId!)
      })
    })
  })

  chrome.tabs.onUpdated.addListener((tabId) => {
    chrome.tabs.get(tabId).then((tab) => {
      if (!isUrl(tab.url) || tab.status !== 'complete') return

      sendCSSInject(tabId)

      heartbeatDetection(tabId, Certificate.CONTENT).catch(() => {
        const { origin } = new URL(tab.url!)
        if (origin) {
          const option = storageStore.docsApis.find((item) => item.origin === origin)
          if (option) {
            chrome.scripting.insertCSS({
              target: { tabId },
              files: ['content/style.css']
            })
            chrome.scripting
              .executeScript({
                target: { tabId },
                files: ['content/index.js']
              })
              .then(() => {
                sendTabMessage(tabId, {
                  type: PostMessageType.CONNECT,
                  data: `${origin}${option.pathname}`
                })
              })
          }
        }
      })

      // chrome.scripting
      //   .executeScript({
      //     target: { tabId },
      //     func() {
      //       function inject(name: string) {
      //         const iframe = document.createElement('iframe')
      //         iframe.srcdoc = `<script type="module">
      //         import('https://cdn.jsdelivr.net/npm/${name}').then((data) => {
      //           console.log(data)
      //         })
      //       </script>`
      //         document.body.append(iframe)
      //       }

      //       window.inject = inject

      //       console.log(inject)

      //       return 'xxxxxx'
      //     }
      //   })
      //   .then(console.log, console.error)
    })
  })
})

// chrome.webRequest.onResponseStarted.addListener(
//   (details) => {
//     console.log(details)
//   },
//   {
//     urls: [
//       'http://main-manage-saas.caas-cloud-test.geega.com/bi-api/api/da/sys-factory-organization/find-work-area-tree?*',
//       'http://main-manage-saas.caas-cloud-test.geega.com/bi-api/api/da/sys-elec-alum-device/findSlots?*'
//     ]
//   }
// )

// chrome?.webRequest.onHeadersReceived.addListener(
//   (details) => {
//     console.log(details)
//     return void 0
//   },
//   {
//     urls: [
//       'http://main-manage-saas.caas-cloud-test.geega.com/bi-api/api/da/sys-factory-organization/find-work-area-tree?*',
//       'http://main-manage-saas.caas-cloud-test.geega.com/bi-api/api/da/sys-elec-alum-device/findSlots?*'
//     ]
//   },
//   ['responseHeaders', 'extraHeaders']
// )

// chrome.webRequest.onCompleted.addListener(
//   (details) => {
//     console.log(details)
//   },
//   {
//     urls: [
//       'http://main-manage-saas.caas-cloud-test.geega.com/bi-api/api/da/sys-factory-organization/find-work-area-tree?*',
//       'http://main-manage-saas.caas-cloud-test.geega.com/bi-api/api/da/sys-elec-alum-device/findSlots?*'
//     ]
//   }
// )
